export const INPUT_VAL = 'input'
export const SELECT_VAL = 'select'
export const NUMERICAL_VAL = 'numerical'
export const DATE_VAL = 'date'
const UK = "UK";
export const input_judgment_logic_options = [
  {
    label: "应填",
    value: "filled",
  },
  {
    label: "不应填",
    value: "non_filled",
  },
]
export const select_judgment_logic_options = [
  {
    label: "应选",
    value: "select",
  },
  {
    label: "不应选",
    value: "non_select",
  },
]
export const date_judgment_logic_options = [
  {
    label: "大于",
    value: "more_than",
  },
  {
    label: "大于等于",
    value: "greater_or_equal",
  },
  {
    label: "小于",
    value: "less_than",
  },
  {
    label: "小于等于",
    value: "less_than_or_equal",
  },
]

import { Message } from 'element-ui'
import intersection from "lodash.intersection";
import request from "@/utils/request";
import moment from "dayjs";
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
moment.extend(isSameOrAfter)
moment.extend(isSameOrBefore)

// let mm1 = moment('2010-10-20').isAfter('2010-10-19');
// let mm2 = moment('2010-10-20').isSameOrAfter('2010-10-19');
// let mm3 = moment('2010-10-20').isBefore('2010-10-19');
// let mm4 = moment('2010-10-20').isSameOrBefore('2010-10-19');
// console.log(mm1)
// console.log(mm2)
// console.log(mm3)
// console.log(mm4)

// let check_rules = [
//     {
//         "model": "input",
//         "modelName": "应填规则",
//         "trigger_field": "fieldQJ1iSd4Jeh",
//         "trigger_field_details": {
//             "label": "性别",
//             "label_origin": "性别YnOCyQNbU0",
//             "value": "fieldQJ1iSd4Jeh",
//             "optionList": [
//                 {
//                     "label": "男",
//                     "value": "男"
//                 },
//                 {
//                     "label": "女",
//                     "value": "女"
//                 }
//             ],
//             "tplId": "61d021fee6e39015b45bdda0",
//             "tplName": "患者"
//         },
//         "trigger_logic": [
//             "女"
//         ],
//         "trigger_logic_details": [
//             {
//                 "label": "女",
//                 "value": "女"
//             }
//         ],
//         "judgment_field": "fieldY8XmZO57eP",
//         "judgment_field_details": {
//             "label": "妇科疾病",
//             "label_origin": "妇科疾病DgRbTzVN1v",
//             "value": "fieldY8XmZO57eP",
//             "tplId": "61d021fee6e39015b45bdda0",
//             "tplName": "患者"
//         },
//         "judgment_logic": "filled",
//         "reference_value": [

//         ],
//         "reference_value_details": [

//         ],
//         "error_prompt": "妇科疾病必须填写，可以填写无",
//         "id": "gZkNFDz3PI"
//     },
//     {
//         "model": "select",
//         "modelName": "应选规则",
//         "trigger_field": "fieldX4D5OBcIW6",
//         "trigger_field_details": {
//             "label": "开关",
//             "label_origin": "开关Gm4GaS8eaA",
//             "value": "fieldX4D5OBcIW6",
//             "optionList": [
//                 {
//                     "value": true,
//                     "label": "是"
//                 },
//                 {
//                     "value": false,
//                     "label": "否"
//                 }
//             ],
//             "tplId": "61d02211e6e39015b45bdda1",
//             "tplName": "资料"
//         },
//         "trigger_logic": [
//             true
//         ],
//         "trigger_logic_details": [
//             {
//                 "value": true,
//                 "label": "是"
//             }
//         ],
//         "judgment_field": "fieldYJpuokCDmw",
//         "judgment_field_details": {
//             "label": "单选框组",
//             "label_origin": "单选框组FaIPlfZekM",
//             "value": "fieldYJpuokCDmw",
//             "optionList": [
//                 {
//                     "label": "选项一",
//                     "value": "选项一"
//                 },
//                 {
//                     "label": "选项二",
//                     "value": "选项二"
//                 }
//             ],
//             "tplId": "61d02211e6e39015b45bdda1",
//             "tplName": "资料"
//         },
//         "judgment_logic": "select",
//         "reference_value": [
//             "选项一",
//             "选项二"
//         ],
//         "reference_value_details": [
//             {
//                 "label": "选项一",
//                 "value": "选项一"
//             },
//             {
//                 "label": "选项二",
//                 "value": "选项二"
//             }
//         ],
//         "error_prompt": "应该选择",
//         "id": "tFea3gkUdJ"
//     },
//     {
//         "model": "numerical",
//         "modelName": "数值规则",
//         "trigger_field": "fieldX4D5OBcIW6",
//         "trigger_field_details": {
//             "label": "开关",
//             "label_origin": "开关20o68mnnBX",
//             "value": "fieldX4D5OBcIW6",
//             "optionList": [
//                 {
//                     "value": true,
//                     "label": "是"
//                 },
//                 {
//                     "value": false,
//                     "label": "否"
//                 }
//             ],
//             "tplId": "61d02211e6e39015b45bdda1",
//             "tplName": "资料"
//         },
//         "trigger_logic": [
//             true
//         ],
//         "trigger_logic_details": [
//             {
//                 "value": true,
//                 "label": "是"
//             }
//         ],
//         "judgment_field": "fieldJSyjJlfQJG",
//         "judgment_field_details": {
//             "label": "数字",
//             "label_origin": "数字u4lWP4OqmV",
//             "value": "fieldJSyjJlfQJG",
//             "tplId": "61d02211e6e39015b45bdda1",
//             "tplName": "资料"
//         },
//         "judgment_logic": "less_than",
//         "reference_value": [

//         ],
//         "reference_value_details": [

//         ],
//         "reference_field": "fieldHjRUhqtUbo",
//         "reference_field_details": {
//             "label": "数字",
//             "label_origin": "数字9u25mUYB8e",
//             "value": "fieldHjRUhqtUbo",
//             "tplId": "61d02239e6e39015b45bdda3",
//             "tplName": "单表"
//         },
//         "error_prompt": "11",
//         "id": "7r0gosZ0U9"
//     },
//     {
//         "model": "date",
//         "modelName": "日期规则",
//         "trigger_field": "fieldRPBB059jto",
//         "trigger_field_details": {
//             "label": "下拉选择",
//             "label_origin": "下拉选择1mDZx6d0MI",
//             "value": "fieldRPBB059jto",
//             "optionList": [
//                 {
//                     "label": "选项一",
//                     "value": "选项一"
//                 },
//                 {
//                     "label": "选项二",
//                     "value": "选项二"
//                 }
//             ],
//             "tplId": "61d02239e6e39015b45bdda3",
//             "tplName": "单表"
//         },
//         "trigger_logic": [
//             "选项一"
//         ],
//         "trigger_logic_details": [
//             {
//                 "label": "选项一",
//                 "value": "选项一"
//             }
//         ],
//         "judgment_field": "field1ykHvESVF5",
//         "judgment_field_details": {
//             "label": "日期选择",
//             "label_origin": "日期选择V0yLPXLSnX",
//             "value": "field1ykHvESVF5",
//             "tplId": "61d02225e6e39015b45bdda2",
//             "tplName": "重复表"
//         },
//         "judgment_logic": "more_than",
//         "reference_value": [

//         ],
//         "reference_value_details": [

//         ],
//         "reference_field": "fieldxdmOvREDHJ",
//         "reference_field_details": {
//             "label": "日期选择",
//             "label_origin": "日期选择Kpn2WEBCCM",
//             "value": "fieldxdmOvREDHJ",
//             "tplId": "61d02239e6e39015b45bdda3",
//             "tplName": "单表"
//         },
//         "error_prompt": "重复表日期必须大于单表日期",
//         "id": "cMbvOEVo90"
//     }
// ]

function showError(message) {
  Message({
    message,
    type: 'error',
    duration: 3 * 1000
  })
}

/**
 * 处理input
 * @param {Object} check_rule 规则
 * @param {Object} trigger_field_msg 触发字段信息
 * @param {String} trigger_field_msg.field 触发字段
 * @param {String} trigger_field_msg.data 触发字段填写的值
 * @param {Array} judgment_field_msg 判断字段信息
 * judgment_field_msg=[{field:'string 判断字段',data:'string 判断字段填写的值'}]
 */
function handleInput(check_rule, judgment_field_msg, trigger_field_msg) {
  // 如果没有
  if (!check_rule.trigger_field) {
    return handleInputError(check_rule, judgment_field_msg)
  } else if (check_rule.trigger_field === trigger_field_msg.field) {
    if (check_rule.trigger_logic.includes(trigger_field_msg.data)) {
      return handleInputError(check_rule, judgment_field_msg)
    } else {
      return true
    }
  }
}

/**
 * 处理inputError
 * @param {Object} check_rule 规则
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 */
function handleInputError(check_rule, judgment_field_msg) {
  if ((check_rule.judgment_logic === 'filled' && !judgment_field_msg.data) || (check_rule.judgment_logic === 'non_filled' && judgment_field_msg.data)) {
    showError(check_rule.error_prompt)
    return false
  } else {
    return true
  }
}

/**
 * 处理select
 * @param {Object} check_rule 规则
 * @param {Object} trigger_field_msg 触发字段信息
 * @param {String} trigger_field_msg.field 触发字段
 * @param {String} trigger_field_msg.data 触发字段填写的值
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 */
function handleSelect(check_rule, judgment_field_msg, trigger_field_msg) {
  // 如果没有
  if (!check_rule.trigger_field) {
    return handleSelectError(check_rule, judgment_field_msg)
  } else if (check_rule.trigger_field === trigger_field_msg.field) {
    if (check_rule.trigger_logic.includes(trigger_field_msg.data)) {
      return handleSelectError(check_rule, judgment_field_msg)
    } else {
      return true
    }
  }
}

/**
 * 处理selectError
 * @param {Object} check_rule 规则
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 */
function handleSelectError(check_rule, judgment_field_msg) {
  if (
    (check_rule.judgment_logic === 'select' && (!judgment_field_msg.data || !check_rule.reference_value.includes(judgment_field_msg.data)))
    ||
    (check_rule.judgment_logic === 'non_select' && (judgment_field_msg.data || check_rule.reference_value.includes(judgment_field_msg.data)))
  ) {
    showError(check_rule.error_prompt)
    return false
  } else {
    return true
  }
}

/**
 * 处理numerical
 * @param {Object} check_rule 规则
 * @param {Object} trigger_field_msg 触发字段信息
 * @param {String} trigger_field_msg.field 触发字段
 * @param {String} trigger_field_msg.data 触发字段填写的值
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 * @param {Object} reference_field_msg 参考字段信息
 * @param {String} reference_field_msg.field 参考字段
 * @param {String} reference_field_msg.data 参考字段填写的值
 */
function handleNumerical(check_rule, judgment_field_msg, trigger_field_msg, reference_field_msg) {
  // 如果没有
  if (!check_rule.trigger_field) {
    return handleNumericalError(check_rule, judgment_field_msg, reference_field_msg)
  } else if (check_rule.trigger_field === trigger_field_msg.field) {
    if (check_rule.trigger_logic.includes(trigger_field_msg.data)) {
      return handleNumericalError(check_rule, judgment_field_msg, reference_field_msg)
    } else {
      return true
    }
  }
}

/**
 * 处理numericalError
 * @param {Object} check_rule 规则
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 * @param {Object} reference_field_msg 参考字段信息
 * @param {String} reference_field_msg.field 参考字段
 * @param {String} reference_field_msg.data 参考字段填写的值
 */
function handleNumericalError(check_rule, judgment_field_msg, reference_field_msg) {
  if (!judgment_field_msg.data) {
    // showError(check_rule.error_prompt)
    // return false
    return true
  } else {
    if (reference_field_msg.data && reference_field_msg.data != UK && reference_field_msg.data != 'ND' && reference_field_msg.data != 'NA' && judgment_field_msg.data && judgment_field_msg.data != UK && judgment_field_msg.data != 'ND' && judgment_field_msg.data != 'NA') {
      switch (check_rule.judgment_logic) {
        case 'more_than':
          if (!(Number(judgment_field_msg.data) > Number(reference_field_msg.data))) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;

        case 'greater_or_equal':
          if (!(Number(judgment_field_msg.data) >= Number(reference_field_msg.data))) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;

        case 'less_than':
          if (!(Number(judgment_field_msg.data) < Number(reference_field_msg.data))) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;

        case 'less_than_or_equal':
          if (!(Number(judgment_field_msg.data) <= Number(reference_field_msg.data))) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;
      }
    } else {
      return true
    }
  }
}

/**
 * 处理Date
 * @param {Object} check_rule 规则
 * @param {Object} trigger_field_msg 触发字段信息
 * @param {String} trigger_field_msg.field 触发字段
 * @param {String} trigger_field_msg.data 触发字段填写的值
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 * @param {Object} reference_field_msg 参考字段信息
 * @param {String} reference_field_msg.field 参考字段
 * @param {String} reference_field_msg.data 参考字段填写的值
 */
function handleDate(check_rule, judgment_field_msg, trigger_field_msg, reference_field_msg) {
  // 如果没有
  if (!check_rule.trigger_field) {
    return handleDateError(check_rule, judgment_field_msg, reference_field_msg)
  } else if (check_rule.trigger_field === trigger_field_msg.field) {
    if (check_rule.trigger_logic.includes(trigger_field_msg.data)) {
      return handleDateError(check_rule, judgment_field_msg, reference_field_msg)
    } else {
      return true
    }
  }
}

/**
 * 处理DateError
 * @param {Object} check_rule 规则
 * @param {Object} judgment_field_msg 判断字段信息
 * @param {String} judgment_field_msg.field 判断字段
 * @param {String} judgment_field_msg.data 判断字段填写的值
 * @param {Object} reference_field_msg 参考字段信息
 * @param {String} reference_field_msg.field 参考字段
 * @param {String} reference_field_msg.data 参考字段填写的值
 */
function handleDateError(check_rule, judgment_field_msg, reference_field_msg) {
  if (!judgment_field_msg.data) {
    // showError(check_rule.error_prompt)
    // return false
    return true
  } else {
    if (reference_field_msg.data && reference_field_msg.data != UK && reference_field_msg.data != 'ND' && reference_field_msg.data != 'NA' && judgment_field_msg.data && judgment_field_msg.data != UK && judgment_field_msg.data != 'ND' && judgment_field_msg.data != 'NA') {
      switch (check_rule.judgment_logic) {
        case 'more_than':
          if (judgment_field_msg.data.includes(UK) || reference_field_msg.data.includes(UK)) {
            return handleDateUK(judgment_field_msg.data, reference_field_msg.data, 'more_than', check_rule.error_prompt)
          } else if (!moment(judgment_field_msg.data).isAfter(reference_field_msg.data)) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;

        case 'greater_or_equal':
          if (judgment_field_msg.data.includes(UK) || reference_field_msg.data.includes(UK)) {
            return handleDateUK(judgment_field_msg.data, reference_field_msg.data, 'greater_or_equal', check_rule.error_prompt)
          } else if (!moment(judgment_field_msg.data).isSameOrAfter(reference_field_msg.data)) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;

        case 'less_than':
          if (judgment_field_msg.data.includes(UK) || reference_field_msg.data.includes(UK)) {
            return handleDateUK(judgment_field_msg.data, reference_field_msg.data, 'less_than', check_rule.error_prompt)
          } else if (!moment(judgment_field_msg.data).isBefore(reference_field_msg.data)) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;

        case 'less_than_or_equal':
          if (judgment_field_msg.data.includes(UK) || reference_field_msg.data.includes(UK)) {
            return handleDateUK(judgment_field_msg.data, reference_field_msg.data, 'less_than_or_equal', check_rule.error_prompt)
          } else if (!moment(judgment_field_msg.data).isSameOrBefore(reference_field_msg.data)) {
            showError(check_rule.error_prompt)
            return false
          } else {
            return true
          }
          break;
      }
    } else {
      return true
    }
  }
}

// 处理日期里面包含UK的情况
function handleDateUK(judgment, reference, flag, error_prompt) {
  let valid = true;
  let parts = judgment.toUpperCase().split(/-|\//);
  let [year, month, day] = parts;

  let r_parts = reference.toUpperCase().split(/-|\//);
  let [r_year, r_month, r_day] = r_parts;

  // 如果判断值里有UK,
  // 先判断年，如果有一个UK则不用比较，返回true;
  // 如果都不是UK,判断年是否一致，如果一致则判断月份；
  // 判断月份，如果有一个UK则不用比较，返回true;
  // 如果都不是UK,判断年是否一致，如果一致则判断天；
  // 如果有一个天是UK，则返回true,

  if (r_year !== UK && year !== UK) {
    if (flag === 'more_than') {
      if (!(+year > +r_year)) {
        valid = false
      } else {
        if ((+year === +r_year) && month !== UK) {
          if (r_month !== UK) {
            if (!(+month > +r_month)) {
              valid = false
            }
          }
        }
      }
    } else if (flag === 'greater_or_equal') {
      if (!(+year >= +r_year)) {
        valid = false
      } else {
        if ((+year === +r_year) && month !== UK) {
          if (r_month !== UK) {
            if (!(+month >= +r_month)) {
              valid = false
            }
          }
        }
      }
    } else if (flag === 'less_than') {
      if (!(+year < +r_year)) {
        valid = false
      } else {
        if ((+year === +r_year) && month !== UK) {
          if (r_month !== UK) {
            if (!(+month < +r_month)) {
              valid = false
            }
          }
        }
      }
    } else if (flag === 'less_than_or_equal') {
      if (!(+year <= +r_year)) {
        valid = false
      } else {
        if ((+year === +r_year) && month !== UK) {
          if (r_month !== UK) {
            if (!(+month <= +r_month)) {
              valid = false
            }
          }
        }
      }
    }
  }
  if (!valid) {
    showError(error_prompt)
  }
  return valid
}

/**
 * 获取项目数据
 * @param {String} id 项目id
 * @param {String} data 该表单填写数据
 * @param {String} patientId 该表单所在的患者id
 * @param {String} tplId 本表单的tplId
 * @param {String} success 提交表单数据的函数
 */
export async function handleCheckRules(headers, id, data, patientId, tplId, success) {
  if (patientId) {
    console.log(data)
    let check_rules = []
    try {
      let res = await request(`/project/${id}`, {
        headers,
      });
      if (
        res &&
        res.project &&
        res.project.check_rules &&
        res.project.check_rules.length
      ) {
        check_rules = res.project.check_rules;
        await isHaveJudgmentField(headers, data, check_rules, patientId, tplId, success)
      } else {
        check_rules = [];
        success()
      }
    } catch (error) {
      console.log(error);
    }
  } else {
    success()
  }
}

// 检查是否有判断字段
async function isHaveJudgmentField(headers, data, check_rules, patientId, tplId, success) {
  let list = []; // 判断字段列表
  for (let i = 0; i < check_rules.length; i++) {
    const element = check_rules[i];
    if (element.model === INPUT_VAL) {
      if (intersection(Object.keys(data), element.judgment_field).length) {
        list.push(element);
      }
    } else {
      if (Object.keys(data).includes(element.judgment_field)) {
        list.push(element);
      }
    }
  }
  console.log('isHaveJudgmentField list');
  console.log(list);
  if (list.length) {
    let errorNum = 0
    let allDatas = await request(`/patient/${patientId}/all-datas`, {
      headers,
    });
    console.log(allDatas)
    console.log(list)

    for (let i = 0; i < list.length; i++) {
      const element = list[i];
      console.log(element)

      let judgment_field_msg = {
        field: element.judgment_field,
        data: data[element.judgment_field]
      }
      if (element.model === INPUT_VAL) {
        judgment_field_msg = element.judgment_field.map(item => {
          return {
            field: item,
            data: data[item]
          }
        })
      }
      let trigger_field_msg = {
        field: element.trigger_field,
        data: null
      }
      let reference_field_msg = {
        field: element.reference_field,
        data: null
      }

      // 需要注意的是判断是否触发字段是本表单，如果是的话得取现有的值而不是获取到的值
      if (element.trigger_field_details && element.trigger_field_details.tplId) {
        if (tplId === element.trigger_field_details.tplId) {
          trigger_field_msg.data = data[element.trigger_field]
        } else {
          let trigger_field_data = allDatas.find(ad => ad.project_tpl === element.trigger_field_details.tplId)
          if (trigger_field_data && trigger_field_data.payload && trigger_field_data.payload[element.trigger_field]) {
            trigger_field_msg.data = trigger_field_data.payload[element.trigger_field]
          }
        }
      }

      if (element.model === NUMERICAL_VAL || element.model === DATE_VAL) {
        if (tplId === element.reference_field_details.tplId) {
          reference_field_msg.data = data[element.reference_field]
        } else {
          let reference_field_data = allDatas.find(ad => ad.project_tpl === element.reference_field_details.tplId)
          if (reference_field_data && reference_field_data.payload && reference_field_data.payload[element.reference_field]) {
            reference_field_msg.data = reference_field_data.payload[element.reference_field]
          }
        }
      }

      if (element.model === INPUT_VAL) {
        for (let l = 0; l < judgment_field_msg.length; l++) {
          if (!handleInput(element, judgment_field_msg[l], trigger_field_msg)) {
            errorNum++
            break;
          }
        }
      } else if (element.model === SELECT_VAL) {
        if (!handleSelect(element, judgment_field_msg, trigger_field_msg)) {
          errorNum++
          break;
        }
      } else if (element.model === NUMERICAL_VAL) {
        if (!handleNumerical(element, judgment_field_msg, trigger_field_msg, reference_field_msg)) {
          errorNum++
          break;
        }
      } else if (element.model === DATE_VAL) {
        if (!handleDate(element, judgment_field_msg, trigger_field_msg, reference_field_msg)) {
          errorNum++
          break;
        }
      }
    }

    if (errorNum === 0) {
      success()
    }
  } else {
    success()
  }
}

